package org.dei.perla.sys.core;

import java.util.ArrayList;

import org.dei.perla.parser.statements.Query;
import org.dei.perla.utils.pipe.*;
import org.dei.perla.utils.waiter.Waitable;
import org.dei.perla.utils.waiter.Waiter;

import org.dei.perla.sys.environments.QueryAnalyzer;

public class QueryExecutionAgent extends DefaultAgent<Query, Object>{

	public QueryExecutionAgent(String parName) {
		super(parName);
		QueryAnalyzer queryAnalizer = QueryAnalyzer.getInstance();
		queryAnalizer.start();
	}

	private Waiter<Pipe<Query>> waiter = null;
	
	@Override
	public void setInputPipe(Pipe<Query> defaultPipe) {
		super.setInputPipe(defaultPipe);		
		waiter = new Waiter<Pipe<Query>>();
		waiter.start();
		waiter.addWaitable(pipeInput.getWaitable());
	}
	
	@Override
	public void loop(){
		Waitable<Pipe<Query>> waitable;
		Query toExecute;

		while(true) {
			waitable = waiter.waitNext();
			toExecute = waitable.getParentComponent().dequeue();
			if (toExecute != null) {
				QueryAnalyzer.registerQuery(toExecute);
			} else {
				// Killpacket ricevuto, chiudo la connessione con il DB,
				// termino le pipe, termino il processo
				waiter.removeWaitable(waitable);
				waitable.getParentComponent().stop();
				waiter.stop();
				//TODO rivedere questo punto
				break;
			}
		}
	}


	@Override
	public void respawn() {
		// TODO Auto-generated method stub
		
	}


	@Override
	public ArrayList<String[]> inspect() {
		// TODO Auto-generated method stub
		return null;
	}
	
	
}
